// FileName: Middleware.ts
// ProjectName: miu-club-html
// 作者：区区电脑
// createTime: 2019/9/29

import {HideNavBarRouterNames, ShowTabBarRouterNames} from "@/router/Config";
import $store from "@/store/store";
import {SHOW_NAV_BAR, SHOW_TAB_BAR} from "@/store/MutationTypes";
import UserModel from "@/views/user-center/model/UserModel";

const isShowTabBarRouter = (route: any): boolean => {
    let result: boolean = false;
    for (let i = 0; i < ShowTabBarRouterNames.length; i++) {
        if (ShowTabBarRouterNames[i] === route.name) {
            result = true;
        }
    }
    return result;
};

const isHideNavBarRouter = (route: any): boolean => {
    let result: boolean = false;
    for (let i = 0; i < HideNavBarRouterNames.length; i++) {
        if (HideNavBarRouterNames[i] === route.name) {
            result = true;
        }
    }
    return result;
};

/**
 * 设置显示 tabBar 的路由
 * @param to
 * @param from
 * @param next
 */
const showTabBar = (to: any, from: any, next: any): void => {
    if (isShowTabBarRouter(to)) {
        $store.dispatch(SHOW_TAB_BAR, true);
    } else {
        $store.dispatch(SHOW_TAB_BAR, false);
    }
};

/**
 * 设置隐藏 navBar 的路由
 * @param to
 * @param from
 * @param next
 */
const hideNavBar = (to: any, from: any, next: any): void => {
    if (isHideNavBarRouter(to)) {
        $store.dispatch(SHOW_NAV_BAR, false);
    } else {
        $store.dispatch(SHOW_NAV_BAR, true);
    }
};

/**
 * 校验账号是否授权
 * @param to
 * @param from
 * @param next
 */
const accountAuthorization = (to: any, from: any, next: any): Promise<boolean> => {
    return new Promise(async (resolve, reject) => {
        if (to.name != 'account-auth') {
            let params = {
                idNumber: '',
                mobile: '',
                nickName: '',
                photo: '',
                name: ''
            };
            let result = await UserModel.getUserInfoFromServe(params, true);
            if (!result) {
                resolve(false);
            } else {
                resolve(true);
            }
        } else {
            resolve(true);
        }
    });
};

export {
    showTabBar,
    hideNavBar,
    accountAuthorization
};
